package com.xiaoxu.spzx.user.service.impl;

import com.alibaba.fastjson2.JSON;
import com.xiaoxu.common.exception.XiaoXuException;
import com.xiaoxu.spzx.model.dto.h5.UserLoginDto;
import com.xiaoxu.spzx.model.dto.h5.UserRegisterDto;
import com.xiaoxu.spzx.model.entity.user.UserInfo;
import com.xiaoxu.spzx.model.vo.common.ResultCodeEnum;
import com.xiaoxu.spzx.model.vo.h5.UserInfoVo;
import com.xiaoxu.spzx.user.mapper.UserInfoMapper;
import com.xiaoxu.spzx.user.service.UserInfoService;
import com.xiaoxu.spzx.utils.AuthContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    // 保存用户注册信息
    @Override
    public void save(UserRegisterDto userRegisterDto) {
        // 获取数据
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();

        // 校验验证码 获取数据库的验证码
        String existRedisCode = redisTemplate.opsForValue().get(username);
        //对比redis数据库的验证码
        if (!code.equals(existRedisCode)){
            throw  new XiaoXuException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //验证用户名不能重复 根据用户名查询数据库
         UserInfo userInfo =  userInfoMapper.selectByUserName(username);

        if (userInfo !=null){
            throw new XiaoXuException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //封装数据
        userInfo = new UserInfo(); //先创建才能设置 ,要不然空指针异常

        userInfo.setUsername(username);
        userInfo.setNickName(nickName);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setPhone(username);
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");

        // 保存数据
        userInfoMapper.save(userInfo);

        //注册成功删除redis数据库
        // 删除Redis中的数据
        redisTemplate.delete(username);
    }
   // 登录的方法
    @Override
    public String login(UserLoginDto userLoginDto) {
        //1.得到用户输入的用户名和密码
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();
        //2.根据用户名查询数据库 得到用户信息
        UserInfo userInfo = userInfoMapper.selectByUserName(username);
        if (userInfo ==null){
            throw  new XiaoXuException(ResultCodeEnum.LOGIN_ERROR);
        }
        String databasePassword = userInfo.getPassword();
        //3.根据通过用户名查询的信息,判断密码是否一致?
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!databasePassword.equals(md5Password)){
            throw  new XiaoXuException(ResultCodeEnum.LOGIN_ERROR);
        }
        //4.校验用户是否被禁用?
        if (userInfo.getStatus() == 0 ){
            throw new XiaoXuException(ResultCodeEnum.ACCOUNT_STOP);
        }
        // 登录成功返回token
        String token
                = UUID.randomUUID().toString().replace("-", "");
        // 将数据保存在redis数据库中 key 就是user:login+ token  value 就是userinfo
        redisTemplate.opsForValue().set("user:login"+token,
                JSON.toJSONString(userInfo),
                3, TimeUnit.HOURS);

        return token;
    }
    //获取用户信息
    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
//        //从redis中获取用户信息
//        String userJson = redisTemplate.opsForValue().get("user:login" + token);
//        if (!StringUtils.hasText(userJson)){
//            throw new XiaoXuException(ResultCodeEnum.LOGIN_ERROR);
//        }//等于空
//        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);

        //从ThreadLocal中获取用户信息
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        //将userInfo的值设置给userInfoVo
        UserInfoVo  userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }
}
